package com.dog.basics.sms.impl;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.dog.basics.SmsEntity.SmsParameter;
import com.dog.basics.SmsResult.SmsSendResult;
import com.dog.basics.sms.SmsSender;
import lombok.Data;
import lombok.extern.log4j.Log4j2;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Primary;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Map;

/**
 * 阿里云短信发送器
 *
 * @author Guo
 * @date 2019年4月30日
 */
@Log4j2
@Component
@Data
@ConfigurationProperties(prefix = "user.ztrh.smscode")
//@ConditionalOnProperty(name = "flag", havingValue = "true")
@Primary
public class ZTRHSmsSender implements SmsSender {
    private String username;
    private String password;
    private String signature;
    private String urls = "https://api.mix2.zthysms.com/v2/sendSmsTp";

    @Override
    public SmsSendResult send(SmsParameter parameter) {
        SmsSendResult sendResult = new SmsSendResult();
         String content = new String("【美通科技】您的验证码为" + parameter.getParams() + ",请尽快完成验证.如非本人操作,请忽略此信息.");
        Long tKey= DateUtil.currentSeconds();
        //请求入参
        JSONObject requestJson = new JSONObject();
        //账号
        requestJson.put("username", username);
        requestJson.put("tKey", tKey);
        //明文密码
        requestJson.put("password", SecureUtil.md5(SecureUtil.md5(password) + tKey));
        //模板ID
        requestJson.put("tpId", parameter.getTemplateCode());
        //签名
        requestJson.put("signature",signature);
        //扩展号
        requestJson.put("ext", "");
        //自定义参数
        requestJson.put("extend", "");
        //发送记录集合
        JSONArray records = new JSONArray();
        JSONObject record = new JSONObject();
        //手机号
        record.put("mobile", parameter.getPhoneNumbers());
        //替换变量
        JSONObject param = new JSONObject();
        param.put("valid_code", parameter.getParams());
        record.put("tpContent", param);
        records.add(record);
        requestJson.put("records", records);
        String result = HttpRequest.post(urls)
                .timeout(60000)
                .body(requestJson.toJSONString(2), MediaType.APPLICATION_JSON_UTF8_VALUE).execute().body();

        JSONObject obj = JSONUtil.parseObj(result);
        if ("200".equals(obj.get("code").toString())) {
            sendResult.setSuccess(Boolean.TRUE);
        }else{
            sendResult.setSuccess(Boolean.FALSE);
            sendResult.setMessage("发送短信失败!");
        }

        return sendResult;
    }

}
